package com.example.http;

import com.alibaba.fastjson.JSONObject;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Classname HttpRespServer
 * @Description TODO
 * @Date 2023/4/24 14:57
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class HttpRespServer {

    private HttpExchange httpExchange;


    private OutputStream outputStream;


    public boolean isSender(){
        return httpExchange.getResponseCode()==-1;
    }

    private void wirte(Object obj)  {
        try {
            String response = JSONObject.toJSONString(obj);
            //发送响应数据
            this.httpExchange.getResponseHeaders().set("Content-Type", "text/plain;charset=UTF-8");
            this.httpExchange.sendResponseHeaders(200,response.getBytes(StandardCharsets.UTF_8).length);
            outputStream.write(response.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void writeJson(JSONObject json){
        try {
            String response = json.toJSONString();
            //发送响应数据
            this.httpExchange.getResponseHeaders().set("Content-Type", "application/json;charset=UTF-8");
            this.httpExchange.sendResponseHeaders(200,response.getBytes(StandardCharsets.UTF_8).length);
            outputStream.write(response.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void writeHtml(String html){
        try {
            String response = html;
            //发送响应数据
            this.httpExchange.getResponseHeaders().set("Content-Type", "text/html;charset=UTF-8");
            this.httpExchange.sendResponseHeaders(200,response.getBytes(StandardCharsets.UTF_8).length);
            outputStream.write(response.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    /**
     * 写入文件给客户端
     * @param bytes 文件
     * @param fileName 文件名
     */
    public void writeByte(byte[] bytes,String fileName) throws IOException {
        try {
            Headers headers = this.httpExchange.getResponseHeaders();
            headers.add("Content-Type", "application/octet-stream");
            headers.add("Content-Length", String.valueOf(bytes.length));
            headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
            // 发送响应内容，将文件的二进制数据写入到响应输出流
            this.httpExchange.sendResponseHeaders(200, bytes.length);

            BufferedOutputStream out = new BufferedOutputStream(httpExchange.getResponseBody());
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            int count;
            while ((count = bis.read(buffer)) != -1) {
                out.write(buffer, 0, count);
            }
            out.close();
        }catch (IOException e) {
            e.printStackTrace();
        }


    }

    public HttpRespServer(HttpExchange httpExchange) {
        this.outputStream=httpExchange.getResponseBody();
        this.httpExchange=httpExchange;
    }


}
